package com.hw.core.system.controller;


import com.hw.core.system.entity.User;
import com.hw.core.system.service.UserService;
import com.hw.core.util.PasswordUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.session.HttpServletSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class PublicController {
    private static final Logger logger = LoggerFactory.getLogger( UserController.class );

    @Autowired
    private UserService userService;
    @GetMapping("/")
    public String index(HttpSession session) {
        if (session.getAttribute( "loginUser" ) == null) {
            Subject currentUser = SecurityUtils.getSubject();
            User principal = (User) currentUser.getPrincipal();
            session.setAttribute( "userid", principal.getNickname() + "[" + principal.getId() + "]" );
            session.setAttribute( "loginUser", principal );
        }

        return "index";
    }




    @PostMapping("/login")
    public String login(@Valid User user, BindingResult bindingResult, RedirectAttributes redirectAttributes, HttpSession session) {
        if (bindingResult.hasErrors()) {
            redirectAttributes.addFlashAttribute( "message", bindingResult.getFieldError().getField() + ":" + bindingResult.getFieldError().getDefaultMessage() );
            return "redirect:/login";
        }

        String username = user.getName();

        UsernamePasswordToken token = new UsernamePasswordToken( user.getName(), user.getPassword() );
        token.setRememberMe( true );
        Subject currentUser = SecurityUtils.getSubject();
        try {
            logger.info( "对用户[" + username + "]进行登录验证..验证开始" );
            currentUser.login( token );
            logger.info( "对用户[" + username + "]进行登录验证..验证通过" );
        } catch (UnknownAccountException uae) {
            logger.info( "对用户[" + username + "]进行登录验证..验证未通过,未知账户" );
            redirectAttributes.addFlashAttribute( "message", "未知账户" );
        } catch (IncorrectCredentialsException ice) {
            logger.info( "对用户[" + username + "]进行登录验证..验证未通过,错误的凭证" );
            redirectAttributes.addFlashAttribute( "message", "密码不正确" );
        } catch (LockedAccountException lae) {
            logger.info( "对用户[" + username + "]进行登录验证..验证未通过,账户已锁定" );
            redirectAttributes.addFlashAttribute( "message", "账户已锁定" );
        } catch (ExcessiveAttemptsException eae) {
            logger.info( "对用户[" + username + "]进行登录验证..验证未通过,错误次数过多" );
            redirectAttributes.addFlashAttribute( "message", "用户名或密码错误次数过多" );
        } catch (AuthenticationException ae) {
            logger.info( "对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下" );
            ae.printStackTrace();
            redirectAttributes.addFlashAttribute( "message", "用户名或密码不正确" );
        }

        if (currentUser.isAuthenticated()) {
            logger.info( "用户[" + username + "]登录认证通过" );
            //聊天功能用户名
            User principal = (User) currentUser.getPrincipal();
            session.setAttribute( "userid", principal.getNickname() + "[" + principal.getId() + "]" );
            session.setAttribute( "loginUser", principal );
            return "redirect:/";
        } else {
            logger.info( "用户[" + username + "]登录失败" );
            token.clear();
            return "redirect:/login";
        }
    }
    @PostMapping("resetPwd")
    @ResponseBody
    public String resetPwd(String oldPass, String newPass) {
        Subject currentUser = SecurityUtils.getSubject();
        User loginUser = (User) currentUser.getPrincipal();
        String name = loginUser.getName();
        if (loginUser.getPassword().equals(
                PasswordUtil.getPasswordByUsernameAndPassword( name, oldPass ) )) {
            userService.resetPwd2( loginUser.getId(), PasswordUtil.getPasswordByUsernameAndPassword( name, newPass ) );
            currentUser.logout();
            return "密码成功修改为: " + newPass + "  请牢记！";
        } else {
            return "原密码错误";
        }
    }

    @PostMapping("resetNickName")
    @ResponseBody
    public String resetNickName(String nickname) {
        Subject currentUser = SecurityUtils.getSubject();
        User loginUser = (User) currentUser.getPrincipal();
        userService.resetNickName( loginUser.getId(), nickname );
        currentUser.logout();
        return "修改成功";

    }

    @PostMapping("resetImg")
    @ResponseBody
    public String resetImg(String img) {
        Subject currentUser = SecurityUtils.getSubject();
        User loginUser = (User) currentUser.getPrincipal();
        userService.resetImg( loginUser.getId(), img );
        currentUser.logout();
        return "修改成功";

    }

    @GetMapping("myself")
    public String myself(Model model) {

        Subject currentUser = SecurityUtils.getSubject();
        User loginUser = (User) currentUser.getPrincipal();
        User u =userService.getUserById( loginUser.getId() );
        model.addAttribute( "user",u );
        return "user/myself";
    }
    @GetMapping("{name}")
    public String view(@PathVariable String name) {
        return name;
    }
}
